﻿namespace Admin.NET.Application.Service;

/// <summary>
/// 根据站点过滤菜单树
/// </summary>
[ApiDescriptionSettings(KeepName = true)]
public class BasZhanDianMenuService : BaseService<BasZhanDianMenu>
{
    protected readonly SysMenuService _sysMenuService;

    public BasZhanDianMenuService(IServiceScopeFactory scopeFactory, SysMenuService sysMenuService) : base(scopeFactory)
    {
        _sysMenuService = sysMenuService;
    }

    /// <summary>
    /// 根据站点过滤菜单树
    /// </summary>
    [HttpPost]
    public async Task<List<MenuOutput>> GetLoginMenuTreeByZhanDian(BasZhanDianMenuInput input)
    {
        var list = await _sysMenuService.GetLoginMenuTree();//根据角色权限获取到所有菜单
        if (input.zhanDian == "输血科" && _sysMenuService._userManager.SuperAdmin)
        {
            //如果是超级管理员登录输血科,显示全部菜单
            return list;
        }
        var listMzd = _rep.GetList(a => a.zhanDian == input.zhanDian);
        // list数组第一层是模块菜单, 这里只筛选出模块菜单
        var filteredList = list.Where(b => listMzd.Any(a => a.menuId == b.Id)).ToList();//筛选出指定站点的菜单
        return filteredList;
    }

    /// <summary>
    /// 所有站点菜单配置
    /// </summary>
    public List<BasZhanDianMenuOutput> All()
    {
        return Queryable
            .LeftJoin<SysMenu>((it, menu) => it.menuId == menu.Id)
            .OrderBy((it, menu) => menu.OrderNo)
            .Select<BasZhanDianMenuOutput>()
            .ToList();
    }

    /// <summary>
    /// 所有站点菜单配置
    /// </summary>
    [AllowAnonymous]
    public List<BasZhanDianMenuTreeOutput> AllTree()
    {
        var fenZu = Queryable.GroupBy(a => a.zhanDian).Select(a => new { a.zhanDian }).ToList();

        var list = Queryable
            .LeftJoin<SysMenu>((it, menu) => it.menuId == menu.Id)
            .OrderBy((it, menu) => menu.OrderNo)
            .Select<BasZhanDianMenuOutput>()
            .ToList();

        var tree = new List<BasZhanDianMenuTreeOutput>();
        foreach (var item in fenZu)
        {
            var treeItem = new BasZhanDianMenuTreeOutput()
            {
                menuTitle = item.zhanDian,
                children = list.Where(a => a.zhanDian == item.zhanDian).ToList()
            };
            tree.Add(treeItem);
        }

        return tree;
    }


    /// <summary>
    /// 新增成功后返回主键
    /// </summary>
    public bool AddRange(List<BasZhanDianMenuInput> input)
    {
        _rep.Delete(a => a.zhanDian == input.First().zhanDian);
        return _rep.InsertRange(input.Adapt<List<BasZhanDianMenu>>());
    }

    /// <summary>
    /// 删除
    /// </summary>
    public bool Delete(long id)
    {
        return _rep.DeleteById(id);
    }
}
